package com.example.system.config;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.example.starter.redis.util.RedisValueUtil;
import com.example.starter.weixin.pojo.WxToken;
import com.example.starter.weixin.util.WxUtil;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author 王令
 * @since 2023/5/8
 */
@Slf4j
@Data
@Component
@ConditionalOnProperty(prefix = "com.example.weixin", name = "enabled", havingValue = "true")
public class WxAppletAccessTokenStateMachine implements InitializingBean {

    private static final String accessTokenKey = "ec:wx_applet_access_token";

    private final RedisTemplate<String, Object> redisTemplate;

    @Value("${com.example.weixin.appid}")
    private String appid;
    @Value("${com.example.weixin.secret}")
    private String secret;


    @XxlJob("refreshWxAppletAccessToken")
    public void refreshToken() {
        final WxToken wxToken = WxUtil.obtainAccessToken(appid, secret);
        if (ObjUtil.isNotNull(wxToken.getErrcode())) {
            log.error(">>>>>>>>>>> refresh weixin applet access_token fail: {}", wxToken.getErrmsg());
        }
        redisTemplate.opsForValue().set(accessTokenKey, wxToken.getAccess_token());
    }

    public String getAccessToken() {
        Object accessToken = RedisValueUtil.get(accessTokenKey);
        if (ObjUtil.isNull(accessToken)) {
            this.refreshToken();
            accessToken = RedisValueUtil.get(accessTokenKey);
        }
        return StrUtil.toString(accessToken);
    }

    @Override
    public void afterPropertiesSet() {
        this.refreshToken();
    }
}
